<template>
  <a-layout>
    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '680px' }"
    >
      <a-row :gutter="24">
        <a-col :span="8">
          <h2 style="line-height: 50px;">文档列表</h2>
          <a-table
              v-if="level1.length"
              :columns="columns"
              :row-key="record => record.id"
              :data-source="level1"
              :loading="loading"
              :pagination="false"
              :defaultExpandAllRows="true"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
            <span>
              <a-space size="small">
                <a-button type="primary" @click="edit(record)" size="small">编辑</a-button>
                <a-popconfirm
                    title="删除后不可恢复，确认删除?"
                    ok-text="是"
                    cancel-text="否"
                    @confirm="handleDelete(record)"
                >
                  <a-button type="primary" danger size="small">删除</a-button>
                </a-popconfirm>
              </a-space>
            </span>
              </template>
            </template>
          </a-table>
          <a-alert v-else-if="infoState" message="暂无文档" type="info"/>
          <a-spin v-else/>
        </a-col>
        <a-col :span="16">
          <a-row :align="'middle'" style="margin-bottom: 10px;">
            <a-col :span="20">
              <h2 style="line-height: 50px;">{{ rightTitle }}</h2>
            </a-col>
            <a-col :span="4" style="text-align: right;">
              <a-button type="primary" @click="add()" size="large" class="green-btn">
                新增文档
              </a-button>
            </a-col>
          </a-row>
          <a-form :model="doc" :label-col="{ span: 2 }">
            <a-form-item label="文档名称">
              <a-input v-model:value="doc.name" placeholder="请输入文档名称"/>
            </a-form-item>
            <a-form-item label="父文档">
              <a-tree-select
                  v-model:value="doc.parent"
                  show-search
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="请选择父文档"
                  allow-clear
                  tree-default-expand-all
                  :tree-data="treeSelectData"
                  :fieldNames="{
              children: 'children',
              label: 'name',
              value: 'id'
            }"
              >
              </a-tree-select>
            </a-form-item>
            <a-form-item label="文档顺序">
              <a-input-number style="width: 100%;" :min="1" :max="99999" v-model:value="doc.sort" placeholder="请输入顺序"/>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="contentPreview" size="large">
                <eye-outlined/>
                内容预览
              </a-button>
            </a-form-item>
            <a-form-item>
              <div id="content" style="border: 1px solid #ccc;z-index: 2;">
                <Toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editorRef"
                    :defaultConfig="toolbarConfig"
                    :mode="mode"
                />
                <Editor
                    style="height: 500px; overflow-y: hidden;"
                    v-model="valueHtml"
                    :defaultConfig="editorConfig"
                    :mode="mode"
                    @onCreated="handleCreated"
                />
              </div>
            </a-form-item>
          </a-form>
          <p>
            <a-form layout="inline" style="justify-content: center !important;">
              <a-form-item>
                <a-button type="primary" @click="handleSave()" size="large" style="z-index: 1;">
                  保存
                </a-button>
              </a-form-item>
            </a-form>
          </p>
        </a-col>
      </a-row>

      <a-drawer
          width="1100px"
          v-model:visible="drawerVisible"
          title="内容预览"
          placement="right"
      >
        <div class="drawerClass" v-html="editorContent"></div>
      </a-drawer>
    </a-layout-content>
  </a-layout>
  <!--  <a-modal
        v-model:visible="visible"
        title="文档表单"
        :confirm-loading="confirmLoading"
        @ok="handleOk"
        :ok-text=okText
        cancel-text="取消"
    >
    </a-modal>-->
</template>
<script lang="ts">
import '@wangeditor/editor/dist/css/style.css'
import {defineComponent, onBeforeUnmount, onMounted, ref, shallowRef} from 'vue';
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'

import axios from "axios";
import {message} from "ant-design-vue";
import {Tool} from "@/util/tool";
import {useRoute} from "vue-router";
import {EyeOutlined} from '@ant-design/icons-vue';
import {IEditorConfig} from '@wangeditor/editor'

export default defineComponent({
  name: 'AdminDoc',
  components: {
    EyeOutlined,
    Editor,
    Toolbar
  },
  setup() {
    const route = useRoute();//路由内置的方法
    const docs = ref();
    const doc = ref();
    doc.value = {};
    const nameParam = ref({name: ''});
    const loading = ref(false);
    const rightTitle = ref("文档新增");
    const drawerVisible = ref(false);
    const serverAddr = ref(process.env.VUE_APP_SERVER);

    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()

    // 内容 HTML
    const valueHtml = ref()

    const toolbarConfig = {}
    const editorConfig: Partial<IEditorConfig> = {
      placeholder: '请输入内容...',
      autoFocus: false,
      MENU_CONF: {}
    }

    // 修改 uploadImage 菜单配置
    editorConfig.MENU_CONF!['uploadImage'] = {
      server: serverAddr.value + '/doc/upload/contentImg',
      fieldName: 'file'
    }

    const handleCreated = (editor: any) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }

    const columns = [
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action'
      }
    ];


    const level1 = ref();//树形结构
    level1.value = [];
    const treeSelectData = ref();//树形结构
    treeSelectData.value = [];
    //要查找的节点变量
    let nodeResult: any;

    /**
     * 数据查询
     */
    const handleQuery = () => {
      loading.value = true;
      // axios.get("/doc/findByEbookId?ebookId=" + route.query.ebookId).then((response) => {
      axios.get("/doc/" + route.query.ebookId).then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          docs.value = data.content;
          level1.value = Tool.array2Tree(docs.value, 0);

          //初始化treeSelect的数据
          treeSelectData.value = Tool.copy(level1.value);
          if (Tool.isEmpty(treeSelectData.value)) {
            treeSelectData.value = [];
          }
          treeSelectData.value.unshift({
            name: '无',
            id: '0'
          })

          //检查是否为空
          checkLevel1Empty();
        } else {
          message.error(data.message);
        }
      })
    }

    /**
     * 内容查询
     */
    const handleQueryContent = () => {
      axios.get("/doc/findContent/" + doc.value.id).then((response) => {
        const data = response.data;
        if (data.success) {
          valueHtml.value = data.content;
        } else {
          message.error(data.message);
        }
      })
    }

    /**
     * 根据nodeId查找分类节点的对象
     * @param nodeId
     * @param nodeData
     */
    const findDocNodeById = (nodeId: any, nodeData: any) => {
      if (Tool.isEmpty(nodeData)) {
        return;
      }
      nodeData.forEach((item: any) => {
        if (item.id === nodeId) {
          nodeResult = item;
        } else {
          findDocNodeById(nodeId, item.children);
        }
      })
    }

    /**
     * 设置子节点为disabled
     * @param nodeData
     */
    const setChildrenNodeDisabled = (nodeData: any) => {
      if (Tool.isEmpty(nodeData)) {
        return;
      }
      nodeData.forEach((item: any) => {
        item.disabled = true;
        setChildrenNodeDisabled(item.children);
      })
    }

    let deleteParams: Array<string> = [];

    /**
     * 删除父节点时，查找子节点id
     * @param nodeData
     */
    const putDeleteParams = (nodeData: any) => {
      if (Tool.isEmpty(nodeData)) {
        return;
      }
      nodeData.forEach((item: any) => {
        deleteParams.push(item.id);
        putDeleteParams(item.children);
      })
    }

    // const visible = ref<boolean>(false);
    const confirmLoading = ref<boolean>(false);
    const okText = ref();

    /**
     * 编辑
     * @param record
     */
    const edit = (record: any) => {
      rightTitle.value = "文档编辑";
      valueHtml.value = "";
      //复制一个新对象，这样进行编辑的时候，就不会修改表格数据了
      //doc.value = record，这样写就和表格数据绑定了
      doc.value = Tool.copy(record);
      handleQueryContent();

      //初始化treeSelect的数据
      treeSelectData.value = Tool.copy(level1.value);
      treeSelectData.value.unshift({
        name: '无',
        id: '0'
      })

      //设置TreeSelect的子节点不可用
      findDocNodeById(record.id, treeSelectData.value);
      setChildrenNodeDisabled(nodeResult.children);

      okText.value = "修改";
      // visible.value = true;
    }

    /**
     * 新增
     */
    const add = () => {
      rightTitle.value = "文档新增";
      valueHtml.value = "";
      doc.value = {};
      //设置ebookId的值
      doc.value = {
        ebookId: route.query.ebookId,
        sort: 1
      }

      //初始化treeSelect的数据
      treeSelectData.value = Tool.copy(level1.value);
      if (Tool.isEmpty(treeSelectData.value)) {
        treeSelectData.value = [];
      }
      treeSelectData.value.unshift({
        name: '无',
        id: '0'
      })
      okText.value = "新增";
      // visible.value = true;
    }

    const handleDelete = (record: any) => {
      //获得要删除的id（当前节点和子节点）
      deleteParams = [];
      deleteParams.push(record.id);
      findDocNodeById(record.id, level1.value);
      putDeleteParams(nodeResult.children);

      axios.delete("/doc/delete/" + deleteParams.join()).then((response) => {
        const data = response.data;
        if (data.success) {
          //重新加载列表
          handleQuery()

          message.success("删除成功");

          //初始化右侧表单
          rightTitle.value = "文档新增";
          valueHtml.value = "";
          doc.value = {};
          //设置ebookId的值
          doc.value = {
            ebookId: route.query.ebookId
          }
        }
      })
    }

    const handleSave = () => {
      if (doc.value.id === doc.value.parent) {
        message.error("父文档不能选择自己");
        return;
      }

      confirmLoading.value = true;
      doc.value.content = valueHtml.value;

      axios.post("/doc/save", doc.value).then((response) => {
        confirmLoading.value = false;
        const data = response.data;
        if (data.success) {
          // visible.value = false;

          //重新加载列表
          handleQuery()

          message.success(okText.value + "成功");

          //清空表单数据
          doc.value = {};
          valueHtml.value = "";
          rightTitle.value = "文档新增";
          //设置ebookId的值
          doc.value = {
            ebookId: route.query.ebookId
          }
        } else {
          message.error(data.message);
        }
      })
    }

    const infoState = ref(false);
    const checkLevel1Empty = () => {
      if (level1.value.length === 0) {
        infoState.value = true;
      }
    }


    const editorContent = ref();
    const contentPreview = () => {
      drawerVisible.value = true;
      editorContent.value = valueHtml.value;
    }

    onMounted(() => {
      handleQuery();

      okText.value = "新增";
      //读取电子书的数据
      doc.value = {};
      //设置ebookId的值
      doc.value = {
        ebookId: route.query.ebookId,
        sort: 1
      }
    })

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    return {
      //docs,
      columns,
      loading,
      // visible,
      confirmLoading,
      edit,
      handleSave,
      doc,
      add,
      okText,
      handleDelete,
      nameParam,
      handleQuery,
      level1,
      treeSelectData,
      rightTitle,
      contentPreview,
      infoState,
      drawerVisible,
      editorContent,

      editorRef,
      valueHtml,
      mode: 'default',
      toolbarConfig,
      editorConfig,
      handleCreated
    };
  }
});
</script>
<style scoped>
.ant-avatar {
  width: 50px;
  height: 50px;
  line-height: 50px;
  border-radius: 8%;
  margin: 5px 0;
}

.green-btn {
  background-color: #00b547;
  border-color: #00b547;
}
</style>
